package com.jyw.fragment;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Paint;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.jyw.R;
import com.jyw.activity.AddressesActivity;
import com.jyw.activity.CouponActivity;
import com.jyw.activity.CzActivity;
import com.jyw.activity.FeedbackActivity;
import com.jyw.activity.KefuActivity;
import com.jyw.activity.LoginActivity;
import com.jyw.activity.MallActivity;
import com.jyw.activity.RecommondMineActivity;
import com.jyw.activity.RecommondStatisticActivity;
import com.jyw.dialog.KefuPhoneDialog;
import com.jyw.network.OkHttpManager;
import com.jyw.network.Server;
import com.jyw.pojo.EventBusTypes;
import com.jyw.pojo.UserInfo;

import java.io.IOException;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;
import cn.sharesdk.onekeyshare.ShareContentCustomizeCallback;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;
import cn.sharesdk.wechat.moments.WechatMoments;
import de.greenrobot.event.EventBus;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Request;
import okhttp3.Response;

/**
 * @author simonw
 * @version 1.0
 * @created 2017/1/1
 */

public class MeFragment extends BaseFragment implements View.OnClickListener {
    private View mContentView;
    private LinearLayout layoutLogin, layoutCz;
    private RelativeLayout layoutKefuOnline, layoutKefuPhone, layoutYouhuiquan, layoutAddresses,
            layoutLogout, layoutRecommondMine, layoutRecommondStatistic, layoutFeedback, layoutShare,
            layoutYue, layoutMall;
    private TextView tvPhoneOrLogin, tvZhang, tvYuan;

    private String phoneNum;

    public static MeFragment newInstance() {
        return new MeFragment();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @SuppressLint("InflateParams")
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        return mContentView = LayoutInflater.from(getActivity()).inflate(R.layout.fgt_me, null);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        layoutLogin = (LinearLayout) mContentView.findViewById(R.id.layout_login);
        layoutKefuOnline = (RelativeLayout) mContentView.findViewById(R.id.layout_kefu_online);
        layoutKefuPhone = (RelativeLayout) mContentView.findViewById(R.id.layout_kefu_phone);
        layoutYouhuiquan = (RelativeLayout) mContentView.findViewById(R.id.layout_youhuiquan);
        layoutAddresses = (RelativeLayout) mContentView.findViewById(R.id.layout_addresses);
        layoutLogout = (RelativeLayout) mContentView.findViewById(R.id.layout_logout);
        layoutRecommondMine = (RelativeLayout) mContentView.findViewById(R.id.layout_recommond_mine);
        layoutRecommondStatistic = (RelativeLayout) mContentView.findViewById(R.id.layout_recommond_statistic);
        layoutFeedback = (RelativeLayout) mContentView.findViewById(R.id.layout_feedback);
        layoutShare = (RelativeLayout) mContentView.findViewById(R.id.layout_share);
        layoutYue = (RelativeLayout) mContentView.findViewById(R.id.layout_yue);
        layoutMall = (RelativeLayout) mContentView.findViewById(R.id.layout_mall);
        layoutCz = (LinearLayout) mContentView.findViewById(R.id.layout_cz);
        tvPhoneOrLogin = (TextView) mContentView.findViewById(R.id.tv_phone_or_login);
        tvZhang = (TextView) mContentView.findViewById(R.id.tv_zhang);
        tvYuan = (TextView) mContentView.findViewById(R.id.tv_yuan);
        layoutLogin.setOnClickListener(this);
        layoutKefuOnline.setOnClickListener(this);
        layoutKefuPhone.setOnClickListener(this);
        layoutYouhuiquan.setOnClickListener(this);
        layoutAddresses.setOnClickListener(this);
        layoutLogout.setOnClickListener(this);
        layoutRecommondMine.setOnClickListener(this);
        layoutRecommondStatistic.setOnClickListener(this);
        layoutFeedback.setOnClickListener(this);
        layoutShare.setOnClickListener(this);
        layoutYue.setOnClickListener(this);
        layoutCz.setOnClickListener(this);
        layoutMall.setOnClickListener(this);

        tvZhang.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG); //下划线
        tvYuan.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG); //下划线


        phoneNum = getPrefs().getString("phone", "");
        /*Toast.makeText(getActivity(), "phoneNum-----"+phoneNum, Toast.LENGTH_LONG).show();*/
        if (!phoneNum.equals("")) {
            tvPhoneOrLogin.setText(phoneNum);
            loadUserInfo();
        }
    }

    private void loadUserInfo() {
        Request request = new Request.Builder().
                url(Server.GET_USER_INFO + "?phone_data=" + phoneNum).
                build();
        OkHttpManager.getInstance().getOkHttpClient().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                OkHttpManager.backgroundThreadShortToast(getActivity(), "错误：" + e.toString());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String res = response.body().string();
                if (!res.equals("您还未登陆，请先登陆。")) {
                    final UserInfo userInfo = new Gson().fromJson(res, UserInfo.class);
                    new AsyncTask<Void, Void, Void>() {
                        @Override
                        protected Void doInBackground(Void... params) {
                            return null;
                        }

                        @Override
                        protected void onPostExecute(Void aVoid) {
                            super.onPostExecute(aVoid);
                            tvZhang.setText(userInfo.getC_arr());
                            tvYuan.setText(userInfo.getH_u_balance());
                        }
                    }.execute();
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.layout_login:
                if (phoneNum.equals("")) {
                    startActivity(new Intent(getActivity(), LoginActivity.class));
                }
                break;
            case R.id.layout_kefu_phone:
                KefuPhoneDialog.newInstance().show(getFragmentManager(), "KefuPhoneDialog");
                break;
            case R.id.layout_kefu_online:
                if (phoneNum.equals("")) {
                    startActivity(new Intent(getActivity(), LoginActivity.class));
                } else {
                    startActivity(new Intent(getActivity(), KefuActivity.class));
                }
                break;
            case R.id.layout_youhuiquan:
                if (phoneNum.equals("")) {
                    startActivity(new Intent(getActivity(), LoginActivity.class));
                } else {
                    startActivity(new Intent(getActivity(), CouponActivity.class));
                }
                break;
            case R.id.layout_addresses:
                if (phoneNum.equals("")) {
                    startActivity(new Intent(getActivity(), LoginActivity.class));
                } else {
                    Intent intent = new Intent(getActivity(), AddressesActivity.class);
                    intent.putExtra("isForDefault", true);
                    startActivity(intent);
                }
                break;
            case R.id.layout_logout:
                if (phoneNum.equals("")) {
                    startActivity(new Intent(getActivity(), LoginActivity.class));
                } else {
                    final AlertDialog dialog = new AlertDialog.Builder(getActivity()).setMessage("您确定要登出吗?")
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    logout();
                                }
                            }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                }
                            }).setCancelable(false).create();
                    dialog.show();
                }
                break;
            case R.id.layout_recommond_mine:
                if (phoneNum.equals("")) {
                    startActivity(new Intent(getActivity(), LoginActivity.class));
                } else {
                    startActivity(new Intent(getActivity(), RecommondMineActivity.class));
                }
                break;
            case R.id.layout_recommond_statistic:
                if (phoneNum.equals("")) {
                    startActivity(new Intent(getActivity(), LoginActivity.class));
                } else {
                    startActivity(new Intent(getActivity(), RecommondStatisticActivity.class));
                }
                break;
            case R.id.layout_feedback:
                if (phoneNum.equals("")) {
                    startActivity(new Intent(getActivity(), LoginActivity.class));
                } else {
                    startActivity(new Intent(getActivity(), FeedbackActivity.class));
                }
                break;
            case R.id.layout_share:
                shareGo();
                break;
            case R.id.layout_yue:
                czGo();
                break;
            case R.id.layout_cz:
                czGo();
                break;
            case R.id.layout_mall:
                if (phoneNum.equals("")) {
                    startActivity(new Intent(getActivity(), LoginActivity.class));
                } else {
                    startActivity(new Intent(getActivity(), MallActivity.class));
                }
                break;
        }
    }

    private void czGo() {
        if (phoneNum.equals("")) {
            startActivity(new Intent(getActivity(), LoginActivity.class));
        } else {
            startActivity(new Intent(getActivity(), CzActivity.class));
        }
    }

    private void shareGo() {
        ShareSDK.initSDK(getActivity());
        OnekeyShare oks = new OnekeyShare();
        //关闭sso授权
        //oks.disableSSOWhenAuthorize();
        oks.setShareContentCustomizeCallback(new ShareContentCustomizeCallback() {
            @Override
            public void onShare(Platform platform, Platform.ShareParams shareParams) {
                if (platform.getName().equals(Wechat.NAME)) {
                    shareParams.setShareType(Platform.SHARE_WEBPAGE);
                    shareParams.setTitle("巾衣卫洗衣");
                    shareParams.setUrl("http://www.jinyiwei.com");
                    shareParams.setImageUrl("https://mmbiz.qlogo.cn/mmbiz/qb1jI1g6BJpiayRfJeysh7NPSzdciawcJP9v0GJGMTYmHR5MJAoDLH8RLPoOe1iccWue89JHhUB9E2p5qdSmlxTrQ/0?wx_fmt=png");
                } else if (platform.getName().equals(WechatMoments.NAME)) {
                    shareParams.setTitle("巾衣卫洗衣");
                    shareParams.setUrl("http://www.jinyiwei.com");
                    shareParams.setImageUrl("https://mmbiz.qlogo.cn/mmbiz/qb1jI1g6BJpiayRfJeysh7NPSzdciawcJP9v0GJGMTYmHR5MJAoDLH8RLPoOe1iccWue89JHhUB9E2p5qdSmlxTrQ/0?wx_fmt=png");
                } else if (platform.getName().equals(QQ.NAME)) {
                    shareParams.setTitle("巾衣卫洗衣");
                    shareParams.setTitleUrl("http://www.jinyiwei.com");
                    shareParams.setImageUrl("https://mmbiz.qlogo.cn/mmbiz/qb1jI1g6BJpiayRfJeysh7NPSzdciawcJP9v0GJGMTYmHR5MJAoDLH8RLPoOe1iccWue89JHhUB9E2p5qdSmlxTrQ/0?wx_fmt=png");
                }
            }
        });
        oks.show(getActivity());
    }

    private void logout() {
        Request request = new Request.Builder().
                url(Server.LOGOUT).
                build();
        OkHttpManager.getInstance().getOkHttpClient().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                OkHttpManager.backgroundThreadShortToast(getActivity(), "错误：" + e.toString());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                new AsyncTask<Void, Void, Void>() {
                    @Override
                    protected Void doInBackground(Void... params) {
                        return null;
                    }

                    @Override
                    protected void onPostExecute(Void aVoid) {
                        super.onPostExecute(aVoid);
                        getPrefs().edit().putString("phone", "").apply();
                        phoneNum = "";
                        tvPhoneOrLogin.setText("登录");
                    }
                }.execute();
            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    public void onEventMainThread(EventBusTypes.Base type) {
        if (type instanceof EventBusTypes.LoginSuccess) {
            tvPhoneOrLogin.setText(phoneNum = getPrefs().getString("phone", ""));
            loadUserInfo();
        } else if (type instanceof EventBusTypes.IntegralBalanceChaged) {
            loadUserInfo();
        }
    }
}
